﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Text;
using System;
using System.Collections.Generic;
using System.Net;

namespace ST.Buz.Web.Controllers
{
	[Route("recveddue")]
	public class FinanceRecvDueController : MyBaseController
	{
		#region Ctor
		private readonly IServiceFinanceRecvDue service;
		private VM_RelatedModule[] relatedModules;

		public FinanceRecvDueController(IServiceFinanceRecvDue _service,
			ILogger<FinanceRecvDueController> _logger) : base(_logger)
		{
			service = _service;

			relatedModules = new VM_RelatedModule[]{
				new VM_RelatedModule(){
					id="sys_attachment",
					name="相关附件",
					count=0
				},
				new VM_RelatedModule(){
					id="finance_recv_list",
					name="收款单",
					count=0
				}
			};
		}
		#endregion

		#region Utilities
		private List<SelectListItem> GetBuzTypeOptions(
			string defText = null,
			string defValue = "0"
		)
		{
			List<SelectListItem> lst = new List<SelectListItem>()
			{
				new SelectListItem()
				{
					Value = ((int)FinanceBuzType.加工订单).ToString(),
					Text = "加工订单"
				},
			};
			if (!string.IsNullOrEmpty(defText))
			{
				lst.Insert(0, new SelectListItem(defText, defValue));
			}
			return lst;
		}
		private List<SelectListItem> GetPayRecvStateOptions(
			string defText = null,
			string defValue = "0"
		)
		{
			List<SelectListItem> lst = new List<SelectListItem>()
			{
				new SelectListItem()
				{
					Value = ((int)FinancePayRecvState.未收).ToString(),
					Text = "未收",
				},
				new SelectListItem()
				{
					Value = ((int)FinancePayRecvState.部分已收).ToString(),
					Text = "部分已收",
				},
				new SelectListItem()
				{
					Value = ((int)FinancePayRecvState.已收清).ToString(),
					Text = "已收清",
				},
			};
			if (!string.IsNullOrEmpty(defText))
			{
				lst.Insert(0, new SelectListItem(defText, defValue));
			}
			return lst;
		}

		private VMS_IMS_FinanceRecvDue GetSearchModelFromJson(JObject paras)
		{
			var vm = new VMS_IMS_FinanceRecvDue();
			vm.pnum = TextHelper.GetInt(paras, "pnum");
			vm.psize = TextHelper.GetInt(paras, "psize");
			vm.sortorder = TextHelper.GetString(paras, "sortorder");

			vm.sno = TextHelper.GetString(paras, "sno");
			vm.partnerid = TextHelper.GetIntNullable(paras, "partnerid");
			vm.partnername = TextHelper.GetString(paras, "partnername");
			vm.date_s = TextHelper.GetDateTimeStart(paras, "date_s");
			vm.date_e = TextHelper.GetDateTimeEnd(paras, "date_e");
			vm.state = TextHelper.GetInts(paras, "state");
			vm.ids = TextHelper.GetInts(paras, "ids");
			return vm;
		}
		#endregion

		public IActionResult Index()
		{
			return RedirectToAction("List");
		}

		[ValidateSession]
		[HttpGet("list")]
		public IActionResult List()
		{
			ViewBag.ServiceCode = "FB5C701C69";
			ViewBag.RecvStateOptions = GetPayRecvStateOptions("全部状态", "0");
			ViewBag.BuzTypeOptions = GetBuzTypeOptions("请选择", "0");

			return View();
		}

		[ValidateSession]
		[HttpGet("malllist")]
		public IActionResult MobileAllList()
		{
			ViewBag.ServiceCode = "FB5C701C69";
			ViewBag.RecvStateOptions = GetPayRecvStateOptions("全部状态", "0");
			ViewBag.BuzTypeOptions = GetBuzTypeOptions("请选择", "0");

			return View();
		}

		[HttpPost("searchall")]
		public IActionResult SearchAll([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				searchModel.orgids = new int[] { sessionCurrent.OrgID };
				PageData pageData = service.GetAllPageList(searchModel, sessionCurrent);
				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("mlist/{partnername}")]
		[HttpGet("mlist")]
		public IActionResult MobileList(string partnername = "")
		{
			ViewBag.ServiceCode = "FB5C701C69";
			ViewBag.RecvStateOptions = GetPayRecvStateOptions("全部状态", "0");
			ViewBag.BuzTypeOptions = GetBuzTypeOptions("请选择", "0");
			ViewData["partnername"] = partnername;

			return View();
		}

		[HttpPost("search")]
		public IActionResult Search([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				searchModel.orgids = new int[] { sessionCurrent.OrgID };
				PageData pageData = service.GetPageList(searchModel, sessionCurrent);
				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpGet("add")]
		public IActionResult Add(string buztype, string buzid, string partnerid, string amount)
		{
			ViewBag.ServiceCode = "FB5C701C69";
			ViewBag.RelatedModules = relatedModules;
			try
			{
				int buzType = TextHelper.GetInt(buztype);
				int buzID = TextHelper.GetInt(buzid);
				int partnerID = TextHelper.GetInt(partnerid);
				decimal amountDue = TextHelper.GetDecimal(amount);
				UserSession sessionCurrent = GetSessionFromRequest();

				var vm = service.Gen(buzType, buzID, partnerID, amountDue, sessionCurrent);
				return View("Edit", vm);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开新增页面出错");
				ViewBag.ErrorMsg = "打开新增页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		[ValidateSession]
		[HttpGet("edit/{id}")]
		[HttpGet("edit")]
		public IActionResult Edit(string id)
		{
			ViewBag.ServiceCode = "FB5C701C69";
			ViewBag.RelatedModules = relatedModules;
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = TextHelper.GetInt(id);
				var vm = service.GetEditDetail(rowID, sessionCurrent);
				return View(vm);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				ViewBag.ErrorMsg = "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		[ValidateSession]
		[HttpGet("medit/{id}")]
		[HttpGet("medit")]
		public IActionResult MobileEdit(string id)
		{
			ViewBag.ServiceCode = "FB5C701C69";
			ViewBag.RelatedModules = relatedModules;
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = TextHelper.GetInt(id);
				var vm = service.GetEditDetail(rowID, sessionCurrent);
				return View(vm);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开编辑页面出错");
				ViewBag.ErrorMsg = "打开编辑页面失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		[ValidateSession]
		[HttpPost("save")]
		public IActionResult Save([FromBody] IMS_FinanceRecvDue vm)
		{
			try
			{
				CheckParams();

				//if (vm.Detail.PriceVip <= 0)
				//{
				//	throw new BuzException("商品零售价格设置有误");
				//}
				//if (!string.IsNullOrEmpty(vm.Detail.Detail))//去除换行等字符
				//{
				//	string strDetail = vm.Detail.Detail;
				//	vm.Detail.Detail = strDetail.Replace("\r", "").Replace("\n", "");
				//}
				if (vm.PartnerID <= 0)
				{
					throw new BuzException("请选择客户或供应商");
				}
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = service.AddOrUpdate(vm, sessionCurrent);

				return new JsonResultBase(rowID);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "新增失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("batchsave")]
		public IActionResult BatchSave([FromBody] IMS_FinanceRecvDue[] list)
		{
			try
			{
				CheckParams();
				if (list == null || list.Length == 0)
				{
					throw new ArgumentException("应收款不能为空");
				}
				UserSession sessionCurrent = GetSessionFromRequest();

				//if (vm.Detail.PriceVip <= 0)
				//{
				//	throw new BuzException("商品零售价格设置有误");
				//}
				//if (!string.IsNullOrEmpty(vm.Detail.Detail))//去除换行等字符
				//{
				//	string strDetail = vm.Detail.Detail;
				//	vm.Detail.Detail = strDetail.Replace("\r", "").Replace("\n", "");
				//}
				foreach (var vm in list)
				{
					if (vm.PartnerID <= 0)
					{
						throw new BuzException("请选择客户或供应商");
					}
				}

				var result = service.BatchAdd(list, sessionCurrent);
				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "新增失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("view/{id}")]
		[HttpGet("view")]
		public IActionResult ViewDetail(string id)
		{
			ViewBag.ServiceCode = "FB5C701C69";
			ViewBag.RelatedModules = relatedModules;
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = TextHelper.GetInt(id);

				var vm = service.GetViewDetail(rowID, sessionCurrent);

				return View("View", vm);
			}
			catch (AuthException ex)
			{
				ViewBag.ErrorMsg = ex.Message;
				return View("Error401");
			}
			catch (EntityNotFoundException ex)
			{
				logger.LogError(ex, "打开查看页面出错");
				ViewBag.ErrorMsg = "未找到相关记录或记录已删除，详细错误信息如下：" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error404");
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "打开查看页面出错");
				ViewBag.ErrorMsg = "打开查看页面失败，详细错误信息如下：" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message);
				return View("Error500");
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("mview/{id}")]
		[HttpGet("mview")]
		public IActionResult MobileViewDetail(string id)
		{
			ViewBag.ServiceCode = "FB5C701C69";
			ViewBag.RelatedModules = relatedModules;
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int rowID = TextHelper.GetInt(id);

				var vm = service.GetViewDetail(rowID, sessionCurrent);

				return View("MobileView", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取信息
		/// </summary>
		/// <returns></returns>
		[HttpPost("detail")]
		public IActionResult ViewJson([FromBody] JObject paras)
		{
			try
			{
				CheckParams();
				UserSession sessionCurrent = GetSessionFromRequest();
				int id = TextHelper.GetInt(paras, "id");
				var model = service.GetViewDetail(id, sessionCurrent);
				if (model == null)
				{
					return new JsonResultBase(false, "未找到相关记录", (int)HttpStatusCode.NotFound);
				}

				return new JsonResultBase(model);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[HttpPost("delete")]
		public IActionResult Delete([FromBody] JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var rowID = TextHelper.GetInt(paras, "id");
				var result = service.Delete(rowID, sessionCurrent);
				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[HttpPost("batchdelete")]
		public IActionResult BatchDelete([FromBody] int[] ids)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var result = service.BatchDelete(ids, sessionCurrent);
				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 相关记录查询
		/// </summary>
		/// <param name="paras"></param>
		/// <returns></returns>
		[HttpPost("related")]
		public IActionResult Related([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				searchModel.buzid = TextHelper.GetInt(paras, "infoid");
				searchModel.buztype = TextHelper.GetInt(paras, "type");
				if (!searchModel.buzid.HasValue || searchModel.buzid.Value <= 0 || !searchModel.buztype.HasValue || searchModel.buztype.Value <= 0)
				{
					throw new ArgumentNullException("相关记录ID或类型");
				}
				PageData pageData = service.GetPageList(searchModel, sessionCurrent);

				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (ArgumentNullException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.InternalServerError);
			}
		}

		[HttpPost("count")]
		public IActionResult Count([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				searchModel.buzid = TextHelper.GetInt(paras, "infoid");
				searchModel.buztype = TextHelper.GetInt(paras, "type");
				if (!searchModel.buzid.HasValue || searchModel.buzid.Value <= 0 || !searchModel.buztype.HasValue || searchModel.buztype.Value <= 0)
				{
					throw new ArgumentNullException("相关记录ID或类型");
				}
				var result = service.GetCount(searchModel, sessionCurrent);
				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (ArgumentNullException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 累计欠款信息
		/// </summary>
		/// <param name="paras"></param>
		/// <returns></returns>
		[HttpPost("statistics")]
		public IActionResult Statistics([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				int partnerId = TextHelper.GetInt(paras, "partnerid");
				var result = service.GetStatistics(partnerId);
				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (ArgumentNullException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.InternalServerError);
			}
		}


		[HttpPost("searchbyfrom")]
		public IActionResult SearchByFrom([FromBody] JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();

				int partnerID = TextHelper.GetInt(paras, "partnerid");
				int[] dueIDs = TextHelper.GetInts(paras, "dueids");

				if (partnerID <= 0)
				{
					throw new BuzException("请选择客户或供应商");
				}
				int[] recvState = new int[]{
					(int)FinancePayRecvState.未收,
					(int)FinancePayRecvState.部分已收
				};
				List<IMS_FinanceRecvDue> lstDue = service.Get(partnerID, recvState, dueIDs);

				return new JsonResultBase(lstDue);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}
	}
}
